﻿
using Extentions;
using Microsoft.AspNetCore.Http;
using Microsoft.EntityFrameworkCore;
using Newtonsoft.Json.Linq;
using NPOI.SS.Formula.Functions;
using Senparc.Weixin.Open.WxOpenAPIs;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Linq.Expressions;
using System.Threading.Tasks;
using TrainingReminderSystem.Bll.NetInterface;
using TrainingReminderSystem.Dal;
using TrainingReminderSystem.Model;
using static NPOI.HSSF.Util.HSSFColor;

namespace TrainingReminderSystem.Bll
{
    public partial class SysCustomerBll
    {
        #region 导入

        public AjaxResult<dynamic> Import(IFormCollection form)
        {
            var r = new AjaxResult<dynamic>();
            string base64 = form["file"];
            if (string.IsNullOrEmpty(base64))
            {
                r.Message = "未找到文件!";
                return r;
            }
            string fileName = Base64Helper.SaveFileFromBase64(base64, null, false);
            fileName = Base64Helper.GetFullName(fileName);

            if (string.IsNullOrEmpty(fileName) || System.IO.File.Exists(fileName) == false)
            {
                r.Message = "未找到相关文件";
                return r;
            }
            string error;
            var list = ImportHelper.GetImportData<ImportSysCustomer>(fileName, out error);
            if (!string.IsNullOrEmpty(error))
            {
                r.Message = error;
                return r;
            }
            if (list.Count == 0)
            {
                r.Message = "excel没有数据,请核查";
                return r;
            }
            string host = ExHttpContext.ServerHost.ExRemoveLast();
            string tokenInfo = PcLoginedBll.Token;
            var sysEmployeeID = PcLoginedBll.CurrentEmployee?.SysEmployeeID;
            var sysStoreID = PcLoginedBll.CurrentStore?.SysStoreID ?? 0;
            Action action = () =>
            {
                int addCount = 0;
                int errCount = 0;
                using (var db = PcLoginedBll.Db)
                {
                    //错误数据的表格
                    var errList = new List<ImportSysCustomer>();
                    Stopwatch sw = new Stopwatch();
                    sw.Start();
                    foreach (var item in list)
                    {
                        var currentIndex = (list.IndexOf(item) + 1);
                        if (currentIndex % 10 == 0)
                        {
                            WebSocketBll.Send(new WebSocketMessage<WebSocketProcessInfo>()
                            {
                                EnumWebSocketMessage = EnumWebSocketMessage.进度条消息,
                                Message = $"总数据{list.Count}条,当前第{currentIndex}条!当前耗时:{sw.ElapsedMilliseconds / 1000}秒",
                                Result = new WebSocketProcessInfo()
                                {
                                    Percent = ((decimal)currentIndex / (decimal)list.Count * 100m).ToString("0.00").ExToDecimal(),
                                    Url = string.Empty
                                }
                            }, tokenInfo);
                        }
                        try
                        {
                            //查询
                            var before = db.SysCustomer.Include(m => m.SysCustomerIdCard).FirstOrDefault(m => m.Phone == item.Phone);
                            if (before != null)
                            {
                                r.Message = $"新增失败:手机号已存在";
                                r.Success = false;
                                //return r;
                                item.Error = r.Message;
                                errList.Add(item);
                                errCount++;
                                continue;
                            }
                            var model = new SysCustomer()
                            {
                                SysCustomerIdCard = new List<SysCustomerIdCard>()
                                {
                                    new SysCustomerIdCard()
                                    {
                                        CardType = "01",
                                        IdCard = item.IdCard
                                    }
                                },
                                SysCustomerName = item.SysCustomerName,
                                Phone = item.Phone,
                                EnumSysCustomerSource = EnumSysCustomerSource.员工录入
                            };
                            var validate = Validate(model, true, db);
                            if (validate.Success == false)
                            {
                                r.Message = $"新增失败:{validate.Message}";
                                r.Success = false;
                                //return r;
                                item.Error = r.Message;
                                errList.Add(item);
                                errCount++;
                                continue;
                            }
                            model.CreateSysEmployeeID = sysEmployeeID;
                            model.SysStoreID = sysStoreID;
                            foreach (var idCardInfo in model.SysCustomerIdCard)
                            {
                                idCardInfo.CreateSysEmployeeID = sysEmployeeID;
                            }
                            db.SysCustomer.Add(model);
                            db.SaveChanges();
                            addCount++;
                        }
                        catch (Exception e)
                        {
                            r.Message = $"新增失败:{e.Message}";
                            r.Success = false;
                            //return r;
                            item.Error = e.Message;
                            errList.Add(item);
                            errCount++;
                            continue;
                        }
                    }
                    sw.Stop();
                    if (errList.Count > 0)
                    {
                        var dt = ExportHelper.ListToDataTable(errList);
                        string downFileName = ExportHelper.TableToExcel(dt, null, "/Export/");
                        r.Result = host + downFileName;
                        r.Message = $"操作成功,总耗时:{sw.ElapsedMilliseconds / 1000}秒!成功添加客户数据条数:{addCount}, 导入总数:{list.Count};{(errCount > 0 ? $"存在添加错误的{errCount}个" : "")};excel路径:<a href='{r.Result}' target='_blank'>{r.Result}</a>";
                        WebSocketBll.Send(new WebSocketMessage<WebSocketProcessInfo>()
                        {
                            EnumWebSocketMessage = EnumWebSocketMessage.进度条消息,
                            Message = r.Message,
                            Result = new WebSocketProcessInfo()
                            {
                                Percent = 100,
                                Url = r.Result
                            }
                        }, tokenInfo);
                        return;
                    }
                    r.Message = $"操作成功,总耗时:{sw.ElapsedMilliseconds / 1000}秒!成功添加客户数据条数:{addCount},导入总数:{list.Count} ";
                    r.Success = true;
                    WebSocketBll.Send(new WebSocketMessage<WebSocketProcessInfo>()
                    {
                        EnumWebSocketMessage = EnumWebSocketMessage.进度条消息,
                        Message = r.Message,
                        Result = new WebSocketProcessInfo()
                        {
                            Percent = 100,
                            Url = string.Empty
                        }
                    }, tokenInfo);
                    return;
                }
            };
            Task.Run(action);
            r.Success = true;
            r.Message = "导入线程执行中...";
            return r;
        }

        /// <summary>
        /// 客户导入格式
        /// </summary>
        public class ImportSysCustomer
        {
            /// <summary>
            /// 客户姓名
            /// </summary>
            [ExStringName("客户姓名")]
            public string SysCustomerName { get; set; }
            /// <summary>
            /// 客户电话
            /// </summary>
            [ExStringName("客户电话")]
            public string Phone { get; set; }

            /// <summary>
            /// 证件号(非必填)
            /// </summary>
            [ExStringName("证件号")]
            [ExDefault("")]
            public string IdCard { get; set; }

            /// <summary>
            /// 备注(非必填)
            /// </summary>
            [ExStringName("备注")]
            [ExDefault("")]
            public string Remark { get; set; }

            /// <summary>
            /// 失败原因
            /// </summary>
            [ExStringName("失败原因")]
            public string Error { get; set; } = string.Empty;
        }

        #endregion

        #region 同步数据

        public AjaxResult<string> Sync(int id)
        {
            using var db = PcLoginedBll.Db;
            return Sync(id, db);
        }

        internal AjaxResult<string> Sync(int id, DbEntities db)
        {
            var r = new AjaxResult<string>() { Success = false };
            var model = db.SysCustomer.Include(m => m.SysCustomerIdCard).FirstOrDefault(m => m.SysCustomerID == id);
            if (model == null)
            {
                r.Message = LanguageHelper.NoData;
                return r;
            }
            if (string.IsNullOrEmpty(model.SysCustomerName) || model.SysCustomerIdCard == null || model.SysCustomerIdCard.Count == 0 || string.IsNullOrEmpty(model.SysCustomerIdCard.FirstOrDefault().IdCard))
            {
                r.Message = "姓名和证件号为空!";
                model.CertSearchUpdateTime = DateTime.Now.Date.AddDays(-SysConfig.AutoIntervalTime + 1);
                db.SaveChanges();
                return r;
            }
            var idCard = model.SysCustomerIdCard.FirstOrDefault().IdCard;
            if (idCard.Length != 18 && idCard.Length != 15)
            {
                r.Message = "证件号格式不对,必须是15或18位";
                model.CertSearchUpdateTime = DateTime.Now.Date.AddDays(-SysConfig.AutoIntervalTime + 1);
                db.SaveChanges();
                return r;
            }
            r = GetInfo(model.SysCustomerName, idCard, "01", "personTypeCode=03");
            if (r.Success == false)
            {
                model.CertSearchUpdateTime = DateTime.Now.Date.AddDays(-SysConfig.AutoIntervalTime + 1);
                db.SaveChanges();
                return r;
            }
            DealData(model, idCard, r.Result);
            db.SaveChanges();
            return r;
        }

        private static AjaxResult<string> GetInfo(string name, string idcardNum, string idcardTypeCode = "01", string last = "personTypeCode=03", int repeatCount = 3)
        {
            var r = CertSearchHelper.GetInfo(name, idcardNum, idcardTypeCode, last);
            if (r.Success == false)
            {
                repeatCount--;
                if (repeatCount <= 0) return r;
                return GetInfo(name, idcardNum, idcardTypeCode, last, repeatCount);
            }
            return r;
        }

        private void DealData(SysCustomer model, string idCard, string json3)
        {
            //[
            //  {
            //    "id": "101952873",
            //    "certStatus": "1",
            //    "name": "何光林",
            //    "sex": "男",
            //    "idcardTypeCode": "01",
            //    "idcardNum": "511131197712293212",
            //    "archivesNum": "A51140051322004234",
            //    "certNum": "T511131197712293212",
            //    "personTypeCode": "03",
            //    "personTypeName": "特种作业人员",
            //    "jobTypeCode": "0301",
            //    "jobTypeName": "电工作业",
            //    "operItemCode": "030102",
            //    "operItemName": "低压电工作业",
            //    "firstCertDate": "2022-10-26",
            //    "shouldReviewDate": "2025-10-25",
            //    "issueOrgName": "眉山市应急管理局",
            //    "reviewDate": "2025-09-01",
            //    "validBeginDate": "2022-10-26",
            //    "validEndDate": "2028-10-25",
            //    "reviewOrgName": "眉山市应急管理局",
            //    "certBlacklist": null,
            //    "oldId": null,
            //    "remarks": "备注：本证书已于2025-09-01在眉山市应急管理局完成复审。请于2028-10-25前进行延期换证。"
            //  },
            //  {
            //    "id": "12848017",
            //    "certStatus": "1",
            //    "name": "何光林",
            //    "sex": "男",
            //    "idcardTypeCode": "01",
            //    "idcardNum": "511131197712293212",
            //    "archivesNum": "A51140051322004234",
            //    "certNum": "T511131197712293212",
            //    "personTypeCode": "03",
            //    "personTypeName": "特种作业人员",
            //    "jobTypeCode": "0301",
            //    "jobTypeName": "电工作业",
            //    "operItemCode": "030102",
            //    "operItemName": "低压电工作业",
            //    "firstCertDate": "2022-10-26",
            //    "shouldReviewDate": "2025-10-25",
            //    "issueOrgName": "眉山市应急管理局",
            //    "reviewDate": null,
            //    "validBeginDate": "2022-10-26",
            //    "validEndDate": "2028-10-25",
            //    "reviewOrgName": null,
            //    "certBlacklist": null,
            //    "oldId": "EC0B9D98F89D4485E050330A156C7623",
            //    "remarks": ""
            //  },
            //  {
            //    "id": "28357650",
            //    "certStatus": "1",
            //    "name": "何光林",
            //    "sex": "男",
            //    "idcardTypeCode": "01",
            //    "idcardNum": "511131197712293212",
            //    "archivesNum": "A51140051322000671",
            //    "certNum": "T511131197712293212",
            //    "personTypeCode": "03",
            //    "personTypeName": "特种作业人员",
            //    "jobTypeCode": "0301",
            //    "jobTypeName": "电工作业",
            //    "operItemCode": "030101",
            //    "operItemName": "高压电工作业",
            //    "firstCertDate": "2022-03-17",
            //    "shouldReviewDate": "2025-03-16",
            //    "issueOrgName": "眉山市应急管理局",
            //    "reviewDate": null,
            //    "validBeginDate": "2022-03-17",
            //    "validEndDate": "2028-03-16",
            //    "reviewOrgName": null,
            //    "certBlacklist": null,
            //    "oldId": "DA86F75614F69AFCE050330A156CE85C",
            //    "remarks": ""
            //  },
            //  {
            //    "id": "96055764",
            //    "certStatus": "1",
            //    "name": "何光林",
            //    "sex": "男",
            //    "idcardTypeCode": "01",
            //    "idcardNum": "511131197712293212",
            //    "archivesNum": "A51140051322000671",
            //    "certNum": "T511131197712293212",
            //    "personTypeCode": "03",
            //    "personTypeName": "特种作业人员",
            //    "jobTypeCode": "0301",
            //    "jobTypeName": "电工作业",
            //    "operItemCode": "030101",
            //    "operItemName": "高压电工作业",
            //    "firstCertDate": "2022-03-17",
            //    "shouldReviewDate": "2025-03-16",
            //    "issueOrgName": "眉山市应急管理局",
            //    "reviewDate": "2024-12-07",
            //    "validBeginDate": "2022-03-17",
            //    "validEndDate": "2028-03-16",
            //    "reviewOrgName": "眉山市应急管理局",
            //    "certBlacklist": null,
            //    "oldId": null,
            //    "remarks": "备注：本证书已于2024-12-07在眉山市应急管理局完成复审。请于2028-03-16前进行延期换证。"
            //  },
            //  {
            //    "id": "28480997",
            //    "certStatus": "5",
            //    "name": "何光林",
            //    "sex": "男",
            //    "idcardTypeCode": "01",
            //    "idcardNum": "511131197712293212",
            //    "archivesNum": "A51000051320005002",
            //    "certNum": "T511131197712293212",
            //    "personTypeCode": "03",
            //    "personTypeName": "特种作业人员",
            //    "jobTypeCode": "0301",
            //    "jobTypeName": "电工作业",
            //    "operItemCode": "0301H4",
            //    "operItemName": "电气试验作业",
            //    "firstCertDate": "2017-04-18",
            //    "shouldReviewDate": "2023-05-10",
            //    "issueOrgName": "四川省应急管理厅",
            //    "reviewDate": null,
            //    "validBeginDate": "2020-05-11",
            //    "validEndDate": "2026-05-10",
            //    "reviewOrgName": null,
            //    "certBlacklist": null,
            //    "oldId": "A566D1F5088C5858E050330A156CE8C2",
            //    "remarks": ""
            //  }
            //]
            var r2 = GetInfo(model.SysCustomerName, idCard, "01", "personTypeCode=02");
            var json2 = r2.Result;
            model.CertSearch02Json = json2;
            model.CertSearch03Json = json3;
            model.CertSearchUpdateTime = DateTime.Now;
            model.Json02MinTime1 = null;
            model.Json02MinTime2 = null;
            model.Json03MinTime1 = null;
            model.Json03MinTime2 = null;
            JArray jArray2 = null;
            JArray jArray3 = null;
            try
            {
                jArray2 = JsonHelper.DeserializeObject(json2) as JArray;
            }
            catch (Exception ex)
            {
            }
            try
            {
                jArray3 = JsonHelper.DeserializeObject(json3) as JArray;
            }
            catch (Exception ex)
            {
            }
            if (jArray2 != null)
            {
                foreach (var item in jArray2)
                {
                    string oldId = item["oldId"].ToString().ExTrim();
                    bool hasRepeat = false;
                    if (!string.IsNullOrEmpty(oldId))
                    {
                        //判断有没重复数据,没有还是要的
                        string name = item["operItemName"].ToString().ExTrim();
                        int count = json2.ExContainsCount(name);
                        if (count > 1)
                        {
                            continue;
                        }
                        hasRepeat = true;
                    }
                    string reviewDate = item["reviewDate"].ToString().ExTrim();
                    if (hasRepeat == false || string.IsNullOrEmpty(reviewDate))
                    {
                        var dtTemp1 = item["shouldReviewDate"].ToString().ExToDateTime();
                        if (model.Json02MinTime1 == null || model.Json02MinTime1.Value > dtTemp1)
                        {
                            model.Json02MinTime1 = dtTemp1;
                        }
                    }
                    var dtTemp2 = item["validEndDate"].ToString().ExToDateTime();
                    if (model.Json02MinTime2 == null || model.Json02MinTime2.Value > dtTemp2)
                    {
                        model.Json02MinTime2 = dtTemp2;
                    }
                }
            }
            if (jArray3 != null)
            {
                foreach (var item in jArray3)
                {
                    string oldId = item["oldId"].ToString().ExTrim();
                    bool hasRepeat = false;
                    if (!string.IsNullOrEmpty(oldId))
                    {
                        //判断有没重复数据,没有还是要的
                        string name = item["operItemName"].ToString().ExTrim();
                        int count = json3.ExContainsCount(name);
                        if (count > 1)
                        {
                            continue;
                        }
                        hasRepeat = true;
                    }
                    string reviewDate = item["reviewDate"].ToString().ExTrim();
                    if (hasRepeat == false || string.IsNullOrEmpty(reviewDate))
                    {
                        var dtTemp1 = item["shouldReviewDate"].ToString().ExToDateTime();
                        if (model.Json03MinTime1 == null || model.Json03MinTime1.Value > dtTemp1)
                        {
                            model.Json03MinTime1 = dtTemp1;
                        }
                    }
                    var dtTemp2 = item["validEndDate"].ToString().ExToDateTime();
                    if (model.Json03MinTime2 == null || model.Json03MinTime2.Value > dtTemp2)
                    {
                        model.Json03MinTime2 = dtTemp2;
                    }
                }
            }
        }

        #endregion
    }
}
